<template>
  <aside class="right-sidebar">
    <div class="contacts">
      <h3 style="margin-top: 0">关注</h3>
      <el-input
        type="text"
        v-model="search"
        placeholder="搜索关注"
        class="search-input"
        style="width: 90%"
        @input="searchContacts"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <ul v-if="contacts">
        <li
          v-for="contact in contacts"
          :key="contact.id"
          @click="goContact(contact.id)"
          class="contact-item"
        >
          <img
            :src="contact.avatar != null ? contact.avatar : '/assets/avatar/default.jpg'"
            alt="Contact Avatar"
            class="contact-avatar"
          />
          <span class="contact-name">{{ contact.username }}</span>
          <!-- 添加取消关注按钮 -->
          <button class="unfollow-btn" @click.stop="unfollowContact(contact.id)">
            取消关注
          </button>
        </li>
      </ul>
    </div>
    <el-skeleton class="" v-if="isLoading" count="5" animated>
     <template #template> 
      <div style="height: 50px; width: auto;padding:10px;display:flex;align-items: center;" >
        <el-skeleton-item variant="image" class="contact-avatar" />
        <el-skeleton-item variant="text" style="width: 50%;" />
      </div>
     </template>
    </el-skeleton>
  </aside>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import userStore from "../store/index";
import { useRouter } from "vue-router";
import api from "../utils/index.js"; // 引入 axios 实例
const userStoreInfo = userStore();
const user = userStoreInfo.getUser();
const userinfo = ref({});
const contacts = ref([]);
const router = useRouter();
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { ElSkeleton } from "element-plus";

let search = ref("");
//加载
const isLoading = ref(true);

const originalContacts = reactive([]);
// 获取用户信息和联系人
const fetchUserInfo = async () => {
  try {
    const response = await api.get(`/users?id=${user.id}`);
    userinfo.value = response.data[0];
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};
// 获取联系人
const fetchContacts = async () => {
  try {
    contacts.value = [];
    for (const id of userinfo.value.contact) {
      const response = await api.get(`/users?id=${id}`);
      contacts.value.push(response.data[0]);
    }
    originalContacts.splice(0, originalContacts.length, ...contacts.value);
  } catch (error) {
    console.error("获取联系人失败:", error);
  }finally {
    isLoading.value = false; // 加载完成
  }
};
// 搜索联系人
const searchContacts = () => {
  // 备份原始联系人数据
  if (search.value.trim()) {
    const searchTerm = search.value.toLowerCase();
    contacts.value = originalContacts.filter((contact) => {
      return contact.username.toLowerCase().includes(searchTerm);
    });
  } else {
    // 搜索框为空时，恢复原始联系人数据
    contacts.value = originalContacts;
  }
};
// 跳转到联系人详情页
const goContact = (id) => {
  router.push({ path: "/userinfo", query: { id } });
};

// 取消关注函数，这里需要根据实际 API 实现
const unfollowContact = async (id) => {
  try {
    // 更新用户信息中的联系人列表
    userinfo.value.contact = userinfo.value.contact.filter(
      (contactId) => contactId !== id
    );
    await api.patch(`/users/${userinfo.value.id}`, { contact: userinfo.value.contact });
    ElMessage.success("取消关注成功");
    fetchContacts();
  } catch (error) {
    ElMessage.error("取消关注失败");
  }
};

// 初始化数据
onMounted(async () => {
  await fetchUserInfo();
  await fetchContacts();
});
</script>

<style scoped>
.right-sidebar {
  background-color: transparent;
  padding: 20px;
  width: 280px;
}

.contacts {
  overflow-y: auto;
}

.contacts ul {
  padding: 0;
  margin: 0;
  text-align: left;
}

.contacts ul li {
  border-radius: 10px;
  margin: 10px 0;
  align-items: center;
  display: flex;
  padding: 8px 12px;
  transition: background-color 0.2s ease;
  position: relative; /* 添加相对定位 */
}

.contacts ul li:hover {
  cursor: pointer;
  background-color: #bababa; /* 鼠标悬停时背景变为灰色 */
}

.contact-search-input {
  width: 100% !important;
  margin-bottom: 10px;
}

.contact-avatar {
  height: 30px;
  width: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.contact-name {
  display: inline-block;
  vertical-align: middle;
}

.el-menu-item:hover {
  background-color: #bababa; /* 鼠标悬停时背景变为灰色 */
  border-radius: 10px;
}

.el-menu-item {
  width: 100%;
  border-radius: 8px;
  margin: 4px 0;
  padding: 12px 16px !important;
  transition: background-color 0.2s ease;
}

.unfollow-btn {
  display: none;
  position: absolute;
  right: 10px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
}

.contacts ul li:hover .unfollow-btn {
  display: block;
}
</style>
